from data_access.database import Session
from sqlalchemy.exc import SQLAlchemyError

from data_access.models.models import Table


class TableDAO:
    def __init__(self):
        self.session = Session()

    def add_table(self, dispatch_code, table_id, database_id, table_name, comment=None):
        new_table = Table(
            dispatch_code=dispatch_code,
            table_id=table_id,
            database_id=database_id,
            table_name=table_name,
            comment=comment
        )
        try:
            self.session.add(new_table)
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()

    def get_table_by_table_id(self, dispatch_code, table_id):
        try:
            return self.session.query(Table).filter(Table.dispatch_code == dispatch_code, Table.table_id == table_id).first()
        except SQLAlchemyError as e:
            return None
        finally:
            self.session.close()

    def update_table(self, table_id, **kwargs):
        try:
            self.session.query(Table).filter(Table.table_id == table_id).update(kwargs)
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()

    def delete_table(self, table_id):
        try:
            self.session.query(Table).filter(Table.table_id == table_id).delete()
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()
